package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.core.domain.entity.SysQuestionRecord;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.NaireTreeSelect;
import com.ruoyi.system.domain.SysDiagnosisTask;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysDiagnosisReport;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 诊断报告Controller
 * 
 * @author ruoyi
 * @date 2022-06-23
 */
@RestController
@RequestMapping("/system/diagnosisreport")
public class SysDiagnosisReportController extends BaseController
{
    @Autowired
    private ISysDiagnosisReportService sysDiagnosisReportService;

    @Autowired
    private ISysNaireService sysNaireService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDiagnosisTaskService sysDiagnosisTaskService;


    @Autowired
    private ISysQuestionService sysQuestionService;

    @Autowired
    private ISysQuestionRecordService sysQuestionRecordService;

    /**
     * 查询诊断报告列表
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDiagnosisReport sysDiagnosisReport)
    {
        startPage();
        List<SysDiagnosisReport> list = sysDiagnosisReportService.selectSysDiagnosisReportList(sysDiagnosisReport);

//        HashMap<Long,HashMap<Long,List<SysDiagnosisReport>>> grouped=new HashMap<>();
//        for(SysDiagnosisReport report :list){
//           if(grouped.containsKey(report.getCompanyId())){
//               HashMap<Long,List<SysDiagnosisReport>> subGroup=grouped.get(report.getCompanyId());
//               if(subGroup.containsKey(report.getNaireId())){
//                   List<SysDiagnosisReport> reports=subGroup.get(report.getNaireId());
//                   reports.add(report);
//               }else {
//                   List<SysDiagnosisReport> reports=new ArrayList<>();
//                   reports.add(report);
//                   subGroup.put(report.getNaireId(),reports);
//               }
//
//           }else{
//               List<SysDiagnosisReport> reports=new ArrayList<>();
//               reports.add(report);
//               HashMap<Long,List<SysDiagnosisReport>> subGroup=new HashMap<>();
//               subGroup.put(report.getNaireId(),reports);
//               grouped.put(report.getCompanyId(),subGroup);
//           }
//        }
//
//        JSONArray comapnys=new JSONArray();
//        int index=1;
//        for(Long companyId:grouped.keySet()){
//            JSONObject company=new JSONObject();
//            company.put("index",index);
//            index+=1;
//            company.put("companyId",companyId);
//            HashMap<Long,List<SysDiagnosisReport>> subGroup=grouped.get(companyId);
//            JSONArray naireArray=new JSONArray();
//            int naire_index=1;
//            for(Long naireId:subGroup.keySet()){
//                JSONObject naire=new JSONObject();
//                List<SysDiagnosisReport>reports=subGroup.get(naireId);
//                JSONArray reportArray=new JSONArray();
//
//                for (SysDiagnosisReport report:reports){
//
//                    JSONObject reportObject=JSONObject.parseObject(JSON.toJSONString(report));
//                    reportObject.put("index",index);
//                    index+=1;
//                    String time=  DateFormatUtils.format(report.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
//                    reportObject.put("createTime",time);
//                    reportArray.add(reportObject);
//                }
//                naire.put("index",index);
//                index+=1;
//                naire.put("naireId",naireId);
//
//                naire.put("children",reportArray);
//                naireArray.add(naire);
//            }
//            company.put("children",naireArray);
//            comapnys.add(company);
//        }


        TableDataInfo table=getDataTable(list);
        HashMap<Long,String> naireNameMap=sysNaireService.getNaireNameMap();
        HashMap<Long,String> companyNameMap=deptService.getCompanyNameMap();
        AjaxResult result=AjaxResult.success();
        result.put("tableInfo",table);
        result.put("naireNameMap",naireNameMap);
        result.put("companyNameMap",companyNameMap);
//        result.put("tableInfo2", JSON.toJSONString(comapnys));
        return result;
    }

    /**
     * 报告自动生成
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:list')")
    @GetMapping("/generate")
    public AjaxResult gen(SysDiagnosisReport sysDiagnosisReport)
    {
        SysDiagnosisTask qtask=new SysDiagnosisTask();
        qtask.setCompanyId(sysDiagnosisReport.getCompanyId());
        qtask.setNaireId(sysDiagnosisReport.getNaireId());

        List<SysDiagnosisTask>tasks=sysDiagnosisTaskService.selectSysDiagnosisTaskList(qtask);
        if(tasks==null||tasks.size()==0)
            return AjaxResult.error("Cannot find the corresponding task");
        SysDiagnosisTask task= tasks.get(0);
        task.setStatus("4");
        sysDiagnosisTaskService.updateSysDiagnosisTask(task);

        int row=sysDiagnosisReportService.generateSysDiagnosisReportByReportId(sysDiagnosisReport);
        return toAjax(row);
    }

    /**
     * 报告自动生成
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:list')")
    @GetMapping("/statistics")
    public AjaxResult statistics(SysDiagnosisReport sysDiagnosisReport)
    {
        SysDept d_query=new SysDept();
        d_query.setParentId(0L);
        List<SysDept>companys=deptService.selectDeptList(d_query);
        List<SysQuestionRecord> records=sysQuestionRecordService.selectSysQuestionRecordList(new SysQuestionRecord());
        List<Long>ids=new ArrayList<>();
       for (SysQuestionRecord record:records){
           if(ids.contains(record.getCompanyId()))
               continue;
           ids.add(record.getCompanyId());

       }
        boolean first=true;
       String result="";
      for (SysDept company:companys){
          if(!ids.contains(company.getDeptId()))
              continue;
          List<String>otherInfo=new ArrayList<>();
          otherInfo.add(company.getDeptId()+"");
          otherInfo.add(company.getDeptName()+"");
        SysQuestion q_query=new SysQuestion();
        q_query.setCompanyId(company.getDeptId());
        q_query.setNaireId(101L);
        List<NaireTreeSelect> ntree=sysQuestionService.getSurveyTreeSelectWithRecord(q_query);
        if(first){
            List<String>labelInfo=new ArrayList<>();
            labelInfo.add("编号");
            labelInfo.add("公司名称");
            result+= printNaireTree(ntree,true,labelInfo)+"\n";
            first=false;
        }

          result+= printNaireTree(ntree,false,otherInfo)+"\n";
      }
        System.out.println(result);


        return toAjax(1);
    }
    private String printNaireTree( List<NaireTreeSelect> ntree,Boolean onlyLabel,List<String>otherInfo){
        List<String> out=new ArrayList<>();
       if (onlyLabel){
           out=getOutputLabelString("",ntree);

       }else{
           out=getOutputValueString(ntree);
       }
        otherInfo.addAll(out);
        String result=String.join("\t", (String[]) otherInfo.toArray(new String[0]));
        return result;
    }


    private List<String> getOutputLabelString(String header,List<NaireTreeSelect> ntree){
        List<String> out=new ArrayList<>();
        for (NaireTreeSelect sntree:ntree){
            String sheader=header+sntree.getLabel()+"-";
            if(sntree.getChildren()!=null&& sntree.getChildren().size()>0){
                List<String> sout=  getOutputLabelString(sheader,sntree.getChildren());
                out.addAll(sout);
            }else{
                if(sntree.getQuestions()!=null&&sntree.getQuestions().size()>0){
                    for (SysQuestion question:sntree.getQuestions()){
                        String theader=sheader+question.getLabel();
                        out.add(theader);
                    }
                }
            }
        }
        return out;
    }

    private List<String> getOutputValueString(List<NaireTreeSelect> ntree){
        List<String> out=new ArrayList<>();
        for (NaireTreeSelect sntree:ntree){
            if(sntree.getChildren()!=null&& sntree.getChildren().size()>0){
                List<String> sout=  getOutputValueString(sntree.getChildren());
                out.addAll(sout);
            }else{
                if(sntree.getQuestions()!=null&&sntree.getQuestions().size()>0){
                    for (SysQuestion question:sntree.getQuestions()){
                        String value="";
                        if(question.getRecords()!=null&&question.getRecords().size()>0){
                            value=question.getRecords().get(0).getAnswer();
                        }
                        else{
                            value="-";
                        }
                        out.add(value);
                    }
                }
            }
        }
        return out;
    }

    /**
     * 导出诊断报告列表
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:export')")
    @Log(title = "诊断报告", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDiagnosisReport sysDiagnosisReport)
    {
        List<SysDiagnosisReport> list = sysDiagnosisReportService.selectSysDiagnosisReportList(sysDiagnosisReport);
        ExcelUtil<SysDiagnosisReport> util = new ExcelUtil<SysDiagnosisReport>(SysDiagnosisReport.class);
        util.exportExcel(response, list, "诊断报告数据");
    }

    /**
     * 获取诊断报告详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:query')")
    @GetMapping(value = "/{reportId}")
    public AjaxResult getInfo(@PathVariable("reportId") Long reportId)
    {
        return AjaxResult.success(sysDiagnosisReportService.selectSysDiagnosisReportByReportId(reportId));
    }

    /**
     * 新增诊断报告
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:add')")
    @Log(title = "诊断报告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysDiagnosisReport sysDiagnosisReport)
    {
        return toAjax(sysDiagnosisReportService.insertSysDiagnosisReport(sysDiagnosisReport));
    }

    /**
     * 修改诊断报告
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:edit')")
    @Log(title = "诊断报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysDiagnosisReport sysDiagnosisReport)
    {
        return toAjax(sysDiagnosisReportService.updateSysDiagnosisReport(sysDiagnosisReport));
    }

    /**
     * 删除诊断报告
     */
    @PreAuthorize("@ss.hasPermi('system:diagnosisreport:remove')")
    @Log(title = "诊断报告", businessType = BusinessType.DELETE)
	@DeleteMapping("/{reportIds}")
    public AjaxResult remove(@PathVariable Long[] reportIds)
    {
        return toAjax(sysDiagnosisReportService.deleteSysDiagnosisReportByReportIds(reportIds));
    }
}
